package cn.snailhd.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


public class FileHandle {
	
	/**
	 * 按行读取文本文件内容
	 * @param file
	 * @param encode
	 * @return
	 */
	public static List<String> readText2Line(File file,String encode){
		List<String> list = new ArrayList<String>();
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			isr = new InputStreamReader(new FileInputStream(file),encode);
			br= new BufferedReader(isr);
			String str=null;
			while((str = br.readLine())!=null){
				list.add(str);
			}
			br.close();
			isr.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}
	public static String readText(File file,String encode){
		List<String> list= readText2Line(file,encode);
		StringBuffer sb = new StringBuffer();
		for(String str:list) {
			sb.append(str+"\r\n");
		}
		return sb.toString();
	}
	
	
	
	/**
	 * 按行储存文本文件，默认不追加（直接覆盖）
	 * @param file
	 * @param list
	 * @return
	 */
	public static String writeTxt4List(File file,List<String> list){
		return writeTxt4List(file,list,false);
	}
	
	/**
	 * 按行储存文本文件
	 * @param file
	 * @param list
	 * @param flag   true 为追加
	 * @return
	 */
	public static synchronized  String writeTxt4List(File file,List<String> list,boolean flag){
		BufferedWriter bw =null;
		try {
			bw =  new BufferedWriter(new FileWriter(file,flag));
			for(String str:list){
				bw.write(str);
				bw.newLine();
				bw.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			IoUtils.close(bw);
		}
		
		return file.getAbsolutePath();
	}
	
	/**
	 * 文件检查，若上级目录不存在则创建
	 * @param file
	 * @return
	 */
	public static boolean fileCheck(File file){
		Boolean flag = false;
		if(!file.exists()){
			File parent = file.getParentFile();
			if(!parent.exists()){
				flag= parent.mkdirs();
			}else{
				flag = true;
			}
		}else{
			flag = true;
		}
		return flag;
	}

}
